package com.lzxuni.modules.dataAcquisition;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lzxuni.common.utils.ImageWatermarking;
import com.lzxuni.common.utils.R;
import com.lzxuni.common.utils.StringUtils;
import com.lzxuni.common.utils.UuidUtil;
import com.lzxuni.modules.common.controller.BaseController;
import com.lzxuni.modules.common.entity.FileEntity;
import com.lzxuni.modules.common.service.FileEntityService;
import com.lzxuni.modules.dataAcquisition.entity.ChainLinkProcessIndex;
import com.lzxuni.modules.dataAcquisition.entity.ProductIndex;
import com.lzxuni.modules.dataAcquisition.service.ChainLinkProcessIndexService;
import com.lzxuni.modules.dataAcquisition.service.ProductIndexService;
import com.lzxuni.modules.productdisplay.entity.ProductDisplay;
import com.lzxuni.modules.productdisplay.service.ProductDisplayService;
import com.lzxuni.modules.system.service.BaseAreaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 产品指标 前端控制器
 * </p>
 *
 * @author wzx
 * @since 2019-06-27
 */
@RestController
@RequestMapping("/LR_DataAcquisition/ProductIndex")
public class ProductIndexController extends BaseController {

    @Autowired
    private ProductIndexService productIndexService;

    @Autowired
    private ChainLinkProcessIndexService chainLinkProcessIndexService;

    @Autowired
    private FileEntityService fileEntityService;

    @Autowired
    private ProductDisplayService productDisplayService;

    @Autowired
    private BaseAreaService baseAreaService;


    @RequestMapping("/Form")
    public ModelAndView insert(String parentId, String productId) throws Exception {
        ModelAndView mv = new ModelAndView("/LR_DataAcquisition/ProductIndex/form");
        Boolean bl = false;
        List<ChainLinkProcessIndex> indices = chainLinkProcessIndexService.list(new QueryWrapper<ChainLinkProcessIndex>().eq("parent_id", parentId).orderByAsc("create_time"));
        for (ChainLinkProcessIndex index : indices) {
            if (index.getCollectionType().equals("视频") || index.getCollectionType().equals("图片")) {
                bl = true;
                break;
            }
        }
        String type = "";
        List<ProductIndex> indexList = productIndexService.list(new QueryWrapper<ProductIndex>().eq("product_id", productId).eq("process_id",parentId));
        if (indexList != null && indexList.size() > 0) {
            type = "edit";
        }else{
            type = "save";
        }
        mv.addObject("indices", indices);
        mv.addObject("parentId", parentId);
        mv.addObject("productId", productId);
        mv.addObject("bl", bl);
        mv.addObject("type", type);
        return mv;
    }

    @RequestMapping("/SaveForm")
    public Object insertDo(HttpServletRequest request, String type, String productId, String parentId, int size, FileEntity file, ImageWatermarking imageMark) throws Exception {
        if (type.equals("save")) {
            for (int i = 0; i < size; i++) {
                ProductIndex index = new ProductIndex();
                String uuid = UuidUtil.get32UUID();
                index.setProductIndexId(uuid);
                index.setProductId(productId);
                index.setProcessId(parentId);
                index.setIndexId(request.getParameter("indexId_" + i));
                index.setIndexValue(request.getParameter("indexValue_" + i));
                index.setCollectionType(request.getParameter("collectionType_" + i));
                index.setCollectionValue(request.getParameter("collectionValue_" + i));
                index.setCreateTime(new Date());
                productIndexService.save(index);
                String pics = request.getParameter("indexPics_" + i);
                if (StringUtils.isNotEmpty(pics)) {
                    fileEntityService.insert(pics.replace("&quot;", "\""), uuid, "tp", "indexPic", null);

                    //图片添加文字水印
                    file.setYwId(uuid);
                    file.setYwType("indexPic");
                    List<FileEntity> filelist = fileEntityService.queryListByFileEntity(file);
                    for (FileEntity entity : filelist) {
                        String description = entity.getDescrption();
                        System.out.println("entity = " + entity);
                        System.out.println("description = " + entity.getDescrption());
                        entity.setDescrption("水印");
                        fileEntityService.updateFile(entity);
                        String sourceImg = entity.getRealPath();//源图片地址
                        String address = StringUtils.substringBeforeLast(entity.getRealPath(),"/");
                        String targetImg = address + "/" + entity.getFileName() ; //新存储的地址
                        String stargetImg = address + "/" + entity.getSfileName() ; //新存储的地址
                        System.out.println("targetImg = " + targetImg);
                        System.out.println("stargetImg = " + stargetImg);

                        //水印内容
                        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        String str = "拍摄时间: " + sf.format(new Date());
                        /*String logoText = "拍摄地址: 黑龙江省双鸭山市饶河县";*/
                        ProductIndex productIndex = productIndexService.getById(uuid);
                        ProductDisplay productDisplay = productDisplayService.getById(productIndex.getProductId());

                        String province = "";
                        String city = "";
                        String country = "";
                        if(StringUtils.isNotEmpty(productDisplay.getProvinceId())){
                            province = baseAreaService.getById(productDisplay.getProvinceId()).getAreaName();
                        }
                        if(StringUtils.isNotEmpty(productDisplay.getCityId())){
                            city = baseAreaService.getById(productDisplay.getCityId()).getAreaName() ;
                        }
                        if(StringUtils.isNotEmpty(productDisplay.getCountyId())){
                            country = baseAreaService.getById(productDisplay.getCountyId()).getAreaName();
                        }
                        System.out.println("province = " + province);
                        System.out.println("city = " + city);
                        System.out.println("county = " + country);
                        /*System.out.println("town =" + town);*/
                        /*System.out.println(village);*/
                        /*String logoText = "拍摄地址: 黑龙江省双鸭山市饶河县";*/
                         String logoText = "拍摄地址: " + province + city + country;
                         /*System.out.println(watermark);*/
                         Color color=new Color(255,255,255);
                         /*imageMark.addFontWatermark(sourceImg, targetImg,watermark,color);
                         imageMark.addFontWatermark(sourceImg,stargetImg,watermark,color);*/
                         imageMark.markImageByText(logoText,sourceImg,targetImg,45,color,"JPG",str);
                         imageMark.markImageByText(logoText,sourceImg,stargetImg,45,color,"JPG",str);

                    }
                }
                String files = request.getParameter("indexFiles_" + i);
                if (StringUtils.isNotEmpty(files)) {
                    fileEntityService.insert(files.replace("&quot;", "\""), uuid, "ntp", "indexFile", null);
                }
            }
            return R.ok("保存成功");
        } else if (type.equals("edit")) {
            productIndexService.remove(new QueryWrapper<ProductIndex>().eq("product_id", productId).eq("process_id", parentId));
            for (int i = 0; i < size; i++) {
                ProductIndex index = new ProductIndex();
                String uuid = request.getParameter("productIndexId_" + i);
                if(StringUtils.isEmpty(uuid)){
                    uuid = UuidUtil.get32UUID();
                }
                index.setProductIndexId(uuid);
                index.setProductId(productId);
                index.setProcessId(parentId);
                index.setIndexId(request.getParameter("indexId_" + i));
                index.setIndexValue(request.getParameter("indexValue_" + i));
                index.setCollectionType(request.getParameter("collectionType_" + i));
                index.setCollectionValue(request.getParameter("collectionValue_" + i));
                index.setCreateTime(new Date());
                productIndexService.save(index);
                FileEntity fileEntity = new FileEntity();
                fileEntity.setYwId(uuid);
                fileEntity.setYwType("indexPic");
                fileEntityService.deleteByywIdAndywType(fileEntity);
                String pics = request.getParameter("indexPics_" + i);
                if (StringUtils.isNotEmpty(pics)) {
                    /*fileEntityService.insert(pics.replace("&quot;", "\""), uuid, "tp", "indexPic", null);*/
                    //文字水印通过descrption="水印"标识，避免重复
                    fileEntityService.Imageinsert(pics.replace("&quot;", "\""),uuid,"tp","indexPic");

                    //图片添加文字水印
                    file.setYwId(uuid);
                    file.setYwType("indexPic");
                    List<FileEntity> filelist = fileEntityService.queryListByFileEntity(file);
                    for (FileEntity entity : filelist) {
                        String description = entity.getDescrption();
                        System.out.println("entity = " + entity);
                        System.out.println("description = " + entity.getDescrption());
                        if(StringUtils.isEmpty(entity.getDescrption())){
                            entity.setDescrption("水印");
                            fileEntityService.updateFile(entity);
                            String sourceImg = entity.getRealPath();//源图片地址
                            String address = StringUtils.substringBeforeLast(entity.getRealPath(),"/");
                            System.out.println("图片真实路径 :" + address);
                            String targetImg = address + "/" + entity.getFileName() ; //新存储的地址
                            String stargetImg = address + "/" + entity.getSfileName() ; //新存储的地址
                            System.out.println("targetImg = " + targetImg);
                            System.out.println("stargetImg = " + stargetImg);

                            //水印内容
                            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            String str = "拍摄时间: " + sf.format(new Date());
                            ProductIndex productIndex = productIndexService.getById(uuid);
                            String province = "";
                            String city = "";
                            String country = "";
                            ProductDisplay productDisplay = productDisplayService.getById(productIndex.getProductId());
                            if(StringUtils.isNotEmpty(productDisplay.getProvinceId())){
                                province = baseAreaService.getById(productDisplay.getProvinceId()).getAreaName();
                            }
                            if(StringUtils.isNotEmpty(productDisplay.getCityId())){
                                city = baseAreaService.getById(productDisplay.getCityId()).getAreaName() ;
                            }
                            if(StringUtils.isNotEmpty(productDisplay.getCountyId())){
                                country = baseAreaService.getById(productDisplay.getCountyId()).getAreaName();

                            }
                            /*String town = baseAreaService.getById(productDisplay.getTownId()).getAreaName();*/
                            /*String village = baseAreaService.getById(productDisplay.getVillageId()).getAreaName();*/
                            System.out.println(province);
                            System.out.println(city);
                            System.out.println(country);
                            /*System.out.println(town);*/
                            /*System.out.println(village);*/
                            /*String logoText = "拍摄地址: 黑龙江省双鸭山市饶河县";*/
                            String logoText = "拍摄地址: " + province + city + country;
                            Color color=new Color(255,255,255);
                            /*imageMark.addFontWatermark(sourceImg, targetImg,watermark,color);
                            imageMark.addFontWatermark(sourceImg,stargetImg,watermark,color);*/
                            imageMark.markImageByText(logoText,sourceImg,targetImg,45,color,"JPG",str);
                            imageMark.markImageByText(logoText,sourceImg,stargetImg,45,color,"JPG",str);
                        }
                    }
                }
                fileEntity.setYwType("indexFile");
                fileEntityService.deleteByywIdAndywType(fileEntity);
                String files = request.getParameter("indexFiles_" + i);
                if (StringUtils.isNotEmpty(files)) {
                    fileEntityService.insert(files.replace("&quot;", "\""), uuid, "ntp", "indexFile", null);
                }
            }
            return R.ok("修改成功");
        } else {
            return R.error("操作失败");
        }
    }

    @RequestMapping("/GetData")
    public Object GetData(String parentId, String productId) throws Exception{
        List<ProductIndex> indexList = new ArrayList<>();
        indexList = productIndexService.list(new QueryWrapper<ProductIndex>().eq("product_id", productId).eq("process_id",parentId));
        for (ProductIndex index : indexList) {
            if (index.getCollectionType().equals("视频")) {
                FileEntity fileEntity = new FileEntity();
                fileEntity.setYwId(index.getProductIndexId());
                fileEntity.setYwType("indexFile");
                index.setFileEntityList(fileEntityService.queryListByFileEntity(fileEntity));
            }
        }
        return indexList;
    }

}

